<template>
  <div class="app-container customer-div">
    <div>
      <!--搜索-->
      <el-form
        :inline="true"
        :model="listQuery"
        size="mini"
        label-width="100px"
      >
        <el-form-item label="月份：">
          <el-date-picker
            value-format="yyyy-MM"
            format="yyyy年MM月"
            v-model="listQuery.date"
            type="month"
            placeholder="选择月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="员工姓名:">
          <el-select v-model="listQuery.realName" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门：" >
          <el-cascader
            v-model="listQuery.departmentId"
            :options="data"
            :props="{value:'departmentId',label:'departmentName',emitPath:false}"
            clearable>
          </el-cascader>
        </el-form-item>

        <el-form-item label="事业部：">
          <el-select v-model="listQuery.departmentIds" filterable placeholder="请选择" multiple>
            <el-option :value="item.divsionDeptId" :label="item.divsionDeptName" v-for="item in divisionList" :key="item.divsionDeptId"></el-option>
          </el-select>
      </el-form-item>

        <el-form-item label="跟进是否完成:" label-width="150px">
          <el-select v-model="listQuery.trackingFinished" filterable placeholder="请选择" clearable>
            <el-option :key="1" label="是" :value="1"> </el-option>
            <el-option :key="0" label="否" :value="0"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSearchList()" type="primary">
            查询
          </el-button>
          <el-button
            :loading="btnloading"
            @click="downloadExcel"
            type="primary">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 图表 -->
    <div
      id="employeeFollowEchart"
      style="height: 400px; margin-top: 20px"
      v-loading="loadingChart"
    ></div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="listLoading"
        ref="tableData"
        :data="tableData"
        show-summary
        :summary-method="getSummaries"
        border
        style="width: 100%; margin-top: 20px"
        :height="400"
        >
        <el-table-column label="月份" align="center" min-width="120" prop="date">
        </el-table-column>
        <el-table-column label="员工" align="center" min-width="100" prop="employee">
        </el-table-column>
        <el-table-column label="部门" align="center" min-width="120" prop="departmentName">
        </el-table-column>
        <el-table-column label="客户总数" align="center" min-width="130" prop="allCustomerTotal">
        </el-table-column>
        <el-table-column label="VIP客户" align="center" min-width="130" prop="vipCustomerNum">
        </el-table-column>
        <el-table-column label="大客户" align="center" min-width="130" prop="bigCustomerNum">
        </el-table-column>
        <el-table-column label="基础客户" align="center" min-width="130" prop="baseCustomerNum">
        </el-table-column>
        <el-table-column label="贸易客户" align="center" min-width="130" prop="tradeCustomerNum">
        </el-table-column>
        <el-table-column label="撮合客户" align="center" min-width="130" prop="zCustomerNum">
        </el-table-column>
        <el-table-column label="应跟进客户数" align="center" min-width="130" prop="customerTotal">
        </el-table-column>
        <el-table-column label="跟进完成百分比" align="center" min-width="130" prop="trackingCompletionSchedule">
          <template slot-scope="scope">
            {{scope.row.trackingCompletionSchedule}}%
          </template>
        </el-table-column>
        <el-table-column label="需跟进次数" align="center" min-width="120" prop="needTrackingNum">
        </el-table-column>
        <el-table-column label="未跟进次数" align="center" min-width="120" prop="notTrackingNum">
        </el-table-column>
        <el-table-column label="有效跟进次数" align="center" min-width="120" prop="validTrackingNum">
        </el-table-column>
        <el-table-column label="实际跟进总次数" align="center" min-width="120" prop="realTrackingTotal">
        </el-table-column>
        <el-table-column label="日常跟进次数" align="center" min-width="100" prop="daily">
        </el-table-column>
        <el-table-column label="信息更新" align="center" min-width="100" prop="goods">
        </el-table-column>
        <el-table-column label="拜访跟进次数" align="center" min-width="100" prop="visit">
        </el-table-column>
        <el-table-column label="成交次数" align="center" min-width="100" prop="deal">
        </el-table-column>
        <el-table-column label="询盘数" align="center" min-width="100" prop="inquiryCount">
        </el-table-column>
        <el-table-column label="一口价下单数" align="center" min-width="100" prop="onePriceOrderCount">
        </el-table-column>
        <el-table-column label="客户询盘率" align="center" min-width="100" prop="inquiryRate">
          <template slot-scope="scope">
            {{scope.row.inquiryRate}}%
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { getEmployeeFollowListAPI,employeeTrackingChartAPI } from "@/api/fms.js";
import { getOrderUsersList, } from '@/api/partner';
import { getDeptList } from '@/api/management';
import { divisionDeptList } from '@/api/company.js';
import { formatDate } from "@/utils/date";
import echarts from "echarts";
import "@/utils/jQuery.print";
import { mapGetters } from "vuex";
import time from "time-formater";
const defaultListQuery = {
  date:"",
  realName: "",
  trackingFinished:'',
  departmentId: '',
  departmentIds:'',
};
export default {
  name: "employeeFollowReport",
  data() {
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      userOptionList:[],
      listLoading: false,
      loadingChart: false,
      btnloading:false,
      data: [],
      divisionList: [],
      timeData: [],//图表日期
      dailyData: [],//日常跟进数
      visitData: [],//拜访跟进数
      dealData: [],//成交次数
      totalData:[],//实际跟进总数
    };
  },
  computed: {
    ...mapGetters(["name", "mobile", "userId"]),
  },
  created() {
    this.$nextTick(()=>{
      let now = new Date();
      this.listQuery.date = formatDate(now, "yyyy-MM");
      if(this.$route.query.dataMonth){
        this.listQuery.date = this.$route.query.dataMonth
      }
      this.getUserOptionList()
      this.getBuMenList()
      this.getList()
      this.getDivisionDeptList()
      this.employeeTrackingChart()
    })

  },
  mounted() {
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.tableData.doLayout()
    })
  },
  filters: {},
  components: {},
  methods: {
    getSummaries(param) {
        const { columns, data } = param;
        const sums = [''];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            if(column.property == 'trackingCompletionSchedule' || column.property == 'inquiryRate'){
              sums[index] = (sums[index]/data.length).toFixed(2)+'%'
            }else{
              sums[index] += '';
            }

          } else {
            sums[index] = '--';
          }
        });
        return sums;
    },
   getDaysInMonth(year, month) {
      let days = [];
      let date = new Date(year, month - 1, 1); // 月份是从0开始的，所以减1
      while (date.getMonth() === month - 1) { // 通过比较月份来获取当月的每一天
        let newDay = formatDate(new Date(date), "yyyy-MM-dd");
        days.push(time(newDay).format('MM-DD ddd'));
        date.setDate(date.getDate() + 1);
      }
      return days;
    },
    //获取图表数据
    employeeTrackingChart() {
      this.loadingChart = true;
      const data = JSON.parse(JSON.stringify(this.listQuery));
      delete data.trackingFinished;
      employeeTrackingChartAPI(data).then((res) => {
        this.loadingChart = false;
        this.timeData = res.timeData;
        this.dailyData = res.dailyData;
        this.visitData = res.visitData;
        this.dealData = res.dealData;
        this.totalData = res.totalData;
        this.initChart();
      }).catch(() => {
        this.loadingChart = false;
      })
    },
    // 配置图表
    initChart() {
      const chart = echarts.init(document.getElementById("employeeFollowEchart"));
      let x = []
      let date = new Date(this.listQuery.date+'-01')
      let year = formatDate(date,'yyyy')
      let month = formatDate(date,'M')
      x = this.getDaysInMonth(year,month)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
        },
        legend: {
          show: true,
          data: ['日常跟进数', '拜访跟进数', '成交次数','实际跟进总数'],
        },
        xAxis: [
          {
            type: 'category',
            data: x,
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#4874cb',
              fontSize: 8,
              interval:0,
              formatter: function (value) {
                // 格式化日期为 MM-DD 格式
                return value.split(" ").join("\n")
              }
            },
            axisLine: {
              // 轴线
              show: false
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            position: 'left',
            axisLabel: {
              formatter: '{value}次'
            },
          },
          {
            type: 'value',
            name:'实际跟进总数',
            position: 'right',
            axisLabel: {
              formatter: '{value}次'
            },
          }
        ],
        series: [
          {
            name: '日常跟进数',
            data: this.dailyData,
            type: 'bar',
            yAxisIndex: 0,
            stack: 'Mon',
            itemStyle: {
              color: "#ee822f",
            },
          },
          {
            name: '拜访跟进数',
            data: this.visitData,
            type: 'bar',
            stack: 'Mon',
            itemStyle: {
              color: "#f2ba02",
            },
          },
          {
            name: '成交次数',
            data: this.dealData,
            type: 'bar',
            stack: 'Mon',
            itemStyle: {
              color: "#75bd42",
            },
          },
          {
            name: '实际跟进总数',
            type: 'line',
            yAxisIndex: 1,
            data: this.totalData,
            itemStyle: {
              color: "#4874cb",
            },
          }
        ]
      };
      chart.setOption(option);
    },
    //获取事业部列表
    getDivisionDeptList(){
      divisionDeptList().then((res)=>{
        this.divisionList = res
      })
    },
    //去除不要的children
    forTree(list){
      let newList = list;
      if(newList.length){
        for (let i = 0; i<newList.length; i++){
          if(newList[i].children && newList[i].children.length > 0){
            this.forTree(newList[i].children)
          }else{
            delete newList[i].children;
          }
        }
        return newList
      }
    },

    //获取部门列表
    getBuMenList(){
      getDeptList().then((res)=>{
        this.data = this.forTree(res);
      })
    },
    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList({type:'sale'}).then((res)=>{
        this.userOptionList = res;
      })
    },

    //下载excle
    downloadExcel(){
      let params
      params = JSON.parse(JSON.stringify(this.listQuery));
      params.isExport = 1;
      delete params.pageSize;
      delete params.pageNum;
      this.btnloading = true
      getEmployeeFollowListAPI(params).then((res)=>{
        this.btnloading = false;
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(()=>{
        this.btnloading = false;
      })
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    //获取列表
    getList() {
      this.listLoading = true;
      getEmployeeFollowListAPI(this.listQuery).then((res) => {
        this.listLoading = false;
        this.tableData = res.list;
      }).catch(() => {
        this.listLoading = false;
      })
    },

    handleSearchList() {
      this.getList();
      this.employeeTrackingChart()
    },
  },
};
</script>



